package cn.itcast.test;

import com.sun.org.apache.bcel.internal.generic.RETURN;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @Author: LDeng
 * @Date: 2021-06-15 17:11
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            ExerciseSell exerciseSell = new ExerciseSell();
            exerciseSell.sellTicket();
        }
    }

    public void sellTicket() throws InterruptedException {
        TicketWindow ticketWindow = new TicketWindow(2000);
        //所有线程的集合
        List<Thread> threadList=new ArrayList<>();
        //卖出的票数统计
        List<Integer> selledList=new Vector<>();
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(() -> {
                int selled = ticketWindow.sell(randomAmount());//随机1-5张票
                selledList.add(selled);
            });
            threadList.add(thread);
            thread.start();
        }

        for (Thread thread : threadList) {
            thread.join();
        }
        //统计卖出数量和剩余票数
        //  log.debug("卖出的票数：{}",selledList.stream().mapToInt(i->i).sum());
        //  log.debug("余票数量：{}",ticketWindow.getCount());
        if(selledList.stream().mapToInt(i->i).sum()!=2000){
            System.out.println("卖出的票数：{}"+selledList.stream().mapToInt(i->i).sum());
            System.out.println("余票数量：{}"+ticketWindow.getCount());
        }

    }

    static Random random = new Random();


    //随机1-5
    public static int randomAmount() {
        return random.nextInt(5)+1;
    }


}

class TicketWindow {

    //余票数量
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public synchronized int sell(int amount) {
        if (this.count >= amount) {//余票数量>=购票数量
            this.count -= amount;
            return amount;
        } else {//与票不足
            return 0;
        }
    }

}
